﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Application.Share;
using Windows.Assistance.Domain;
using Windows.Assistance.Infrastructure.EFCore;
using Windows.Infrastructure.Share.Extensions;

namespace Windows.Assistance.Application
{
    public class DictionaryCategoryService : IDictionaryCategoryService
    {
        private readonly AssistanceDbContext _db;
        private readonly IMapper _mapper;
        public DictionaryCategoryService(AssistanceDbContext db, IMapper mapper)
        { 
            _db = db;
            _mapper = mapper;
        }
        /// <summary>
        /// 获取id的字典类型详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<DictionaryCategoryResponse> Detail(int id)
        {
            var model = await _db.DictionaryCategory.FindByIdAsync(id);
            return _mapper.Map<DictionaryCategoryResponse>(model);
        }
        /// <summary>
        /// 字典类型保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task Save(DictionaryCategorySaveRequest request)
        {
            if (await _db.DictionaryCategory.AnyAsync(x => x.Category.ToLower() == request.Category && x.Id != request.Id))
                throw new ApiException("字典类型已存在!");
            if (await _db.DictionaryCategory.AnyAsync(x => x.Name == request.Name && x.Id != request.Id))
                throw new ApiException("字典类型名称已存在!");
            if (request.Id == null)
            {
                DictionaryCategory model = _mapper.Map<DictionaryCategory>(request);
                await _db.DictionaryCategory.AddAsync(model);
            }
            else
            {
                DictionaryCategory? model = await _db.DictionaryCategory.FindByIdAsync(request.Id.Value);
                if (model == null)
                    throw new ApiException("字典类型不存在!");
                model.Category = request.Category;
                model.Name = request.Name;
                model.Remark = request.Remark;
            }
            await _db.SaveChangesAsync();
        }
    }
}
